package db_main

import (
	"errors"
	"fmt"
	global2 "longmen/server/config/global"
	"longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql"
	"longmen/server/pkg/db/mysql/models/models_main"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
	"longmen/server/pkg/common/api_models"
)

/**
 * @author Aaron
 * @description
 * @createTime 16:47 2022/5/25
 **/
func GetActivityReward(id int) ([]*api_models.GetActivityReward, error) {
	// 跨库了，需要修改
	o := make([]*api_models.GetActivityReward, 0)
	err := global2.GetR().
		Raw(
			"SELECT o.props_id AS prop_id,"+
				"p.icon AS prop_icon,"+
				"p.name AS prop_name,"+
				"o.props_duration as prop_duration,"+
				"o.gift_id AS gift_id,"+
				"g.icon AS gift_icon,"+
				"g.title AS gift_name,"+
				"o.quantity AS gift_quantity,"+
				"o.reward_type AS reward_type FROM"+
				" (SELECT r.gift_id,props_id,r.quantity,r.props_duration,r.reward_type "+
				" FROM db_activity a "+
				" LEFT JOIN db_activity_reward r ON a.id = r.activity_id WHERE a.id = ? )  o"+
				" LEFT JOIN live.db_gift g ON o.gift_id = g.id"+
				" LEFT JOIN db_props p ON o.props_id = p.id", id).
		Find(&o).
		Error
	if err != nil {
		return nil, fmt.Errorf("%s%s", util.Convert2(), err.Error())
	}
	return o, nil
}

/**
*注册活动
 */
func RegActivity(uid int) error {
	activityList, err := GetActivityListByParam(map[string]interface{}{"category": _const.RegActivityType}, "", 0, 0)
	if err != nil {
		global2.Log.Errorf("err :%+v", err)
		return err
	}
	activity := new(models_main.Activity)
	tm := time.Now().Unix()
	//从中挑选一个有效活动
	for _, v := range activityList {
		if tm >= v.StartTime.Unix() && tm < v.EndTime.Unix() {
			activity = v
			break
		}
	}

	if activity.Id > 0 {
		recd, _ := GetActivityTypeRecord(uid, _const.RegActivityType)
		if recd.Uid > 0 {
			global2.Log.Errorf("注册活动,uid:%d已经参与过", uid)
			return err
		}
		var reward api_models.TaskReward
		reward.Diamond = activity.Carat   //克拉奖励
		reward.Exp = activity.Experience  //经验奖励
		reward.Gold = activity.EagleDrill //鹰钻奖励
		if reward.Diamond < 1 && reward.Exp < 1 && reward.Gold < 1 {
			return errors.New("奖励不能为空")
		}
		user, err := mysql.GetUserParam(echo.Map{"id": uid})
		if err != nil {
			global2.Log.Errorf("RegActivity user Err:%v", err)
			return err
		}
		tx := global2.GetX().Begin() //------------------DB:事务开始-----------------//
		defer func() {
			if r := recover(); r != nil {
				tx.Rollback()
			}
		}()
		user.Gold += int(reward.Gold)
		user.Point += int(reward.Exp)
		user.Diamond += int(reward.Diamond)
		err = UpdateUserByTransactions(tx, []string{"gold", "point", "diamond"}, user)
		if err != nil {
			global2.Log.Errorf("RegActivity Err:%v", err)
			return err
		}
		profitLogs := GenActivityProfitList(&reward, uid, activity, _const.PROFIT_REG_ACTIVITY)
		err = InsertUserProfitByTransactions(tx, profitLogs)
		if err != nil {
			log.Errorf("InsertUserProfitByTransactions err :%v", err)
			return err
		}
		var activityRecord models_main.UserActivity
		activityRecord.Uid = uint(uid)
		activityRecord.IsReceived = 1
		activityRecord.ActivityId = uint8(activity.Id)
		activityRecord.Category = _const.RegActivityType
		activityRecord.CreatedAt = time.Now()
		activityRecord.Stage = 100
		err = InsertActivityRecord(tx, &activityRecord)
		if err != nil {
			log.Errorf("InsertActivityRecord err :%v", err)
			return err
		}
		tx.Commit()
	}
	return nil
}

// 生成活动账变
func GenActivityProfitList(reward *api_models.TaskReward, uid int, activity *models_main.Activity, consumeType int) []*models_main.UserProfit {
	f_profit_node := func(coinCount int, coinType int) *models_main.UserProfit {
		return &models_main.UserProfit{
			Uid:         uid, //记录的主人
			FUid:        0,   //system
			ConsumeType: consumeType,
			Type:        _const.TYPE_PROFIT, //这是一个赚钱记录

			CoinCount: coinCount,
			Content: fmt.Sprintf("完成活动%s,收到奖励%.2f%s",
				activity.Title, float64(coinCount)/100, util.GetCoinName(coinType)),

			Resid:      int(activity.Id),
			Count:      coinCount,
			CreateTime: time.Now(),
			CoinType:   coinType,
			OrderNo:    util.GenOrderId("GT", 1),
			Liveid:     0,
		}
	}
	var profitLog []*models_main.UserProfit
	if reward.Diamond > 0 {
		profitLog = append(profitLog, f_profit_node(int(reward.Diamond), int(_const.CoinDiamond)))
	}
	if reward.Gold > 0 {
		profitLog = append(profitLog, f_profit_node(int(reward.Gold), int(_const.CoinGold)))
	}
	return profitLog
}
